import axios from 'axios'
import { Toast } from 'vant'
import store from '../store'
import { getToken } from '@/assets/auth'
import Config from '@/settings'
import Cookies from 'js-cookie'
import router from '../router'
import Vue from 'vue'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_BASE_API : '/', // api 的 base_url
  timeout: Config.timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config['cancelToken'] = new axios.CancelToken(function executor(cancel) {
      Vue.prototype.$httpRequestList.push(cancel) // 存储cancle
    })
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    if (!response.data) {
      return Promise.reject(response)
    }

    const code = response.data.code
    // console.log(code);
    if (code && code !== 200) {
      Toast.fail(response.data.msg);
      //   Toast({
      //     title: response.data.msg,
      //     duration: 3000
      //   })
      if (response.data.msg == '权限校验失败') {
        router.push({ name: 'login' })
      }
      return Promise.reject(response.data.msg)
    } else {
      return response.data
    }
  },
  error => {
    if(error.response.data.hasOwnProperty('msg')&&error.response.data.msg.indexOf('权限校验失败')>-1){

      store.dispatch('LogOut').then(() => {
        // 用户登录界面提示
        Cookies.set('point', '401')
        location.reload()
      })
    }
    // 兼容blob下载出错json提示
    if (!error.hasOwnProperty('response')) {
      return
    }
    if (error.response.data instanceof Blob && error.response.data.type.toLowerCase().indexOf('json') !== -1) {
      const reader = new FileReader()
      reader.readAsText(error.response.data, 'utf-8')
      reader.onload = function(e) {
        const errorMsg = JSON.parse(reader.result).error.message
        Toast({
          title: errorMsg,
          duration: 5000
        })
      }
    } else {
      let code = 0
      let status = 200
      try {
        status = error.response.status
        code = error.response.data.code || error.response.data.error.code
      } catch (e) {
        if (error.toString().indexOf('Error: timeout') !== -1) {
          Toast({
            title: '网络请求超时',
            duration: 5000
          })
          return Promise.reject(error)
        }
      }
      if (status == 404) {
        Toast({
          title: '找不到接口',
          duration: 5000
        })
        return Promise.reject(error)
      }
      if (status == 401) {
        store.dispatch('LogOut').then(() => {
          // 用户登录界面提示
          Cookies.set('point', '401')
          router.push({ name: 'login' })
        })
        return Promise.reject(error)
      }

      if (code) {
        if (code == '401') {
          store.dispatch('LogOut').then(() => {
            // 用户登录界面提示
            Cookies.set('point', '401')
            router.push({ name: 'login' })
          })
        } else if (code == '403') {
          this.$goRoute('login')
        } else {
          const errorMsg = error.response.data.error.message
          if (errorMsg !== undefined) {
            Toast({
              title: errorMsg,
              duration: 5000
            })
            this.$goRoute('login')
          }
        }
      } else {
        Toast({
          title: '接口请求失败',
          duration: 5000
        })
      }
    }
    if (!error.data) {
      return Promise.reject(error)
    }
    return Promise.reject(error)
  }
)
export default service
